package com.moyun.modelclass.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.moyun.modelclass.adapter.OrderEvaluateImageAdapter;
import com.moyun.modelclass.adapter.OrderEvaluateModelAdapter;
import com.moyun.modelclass.base.BaseModelActivity;
import com.moyun.modelclass.http.api.OrderDetailsApi;
import com.moyun.modelclass.http.api.OrderEvaluateApi;
import com.moyun.modelclass.http.api.UpdateImageApi;
import com.moyun.modelclass.http.bean.OrderDetailsResponse;
import com.moyun.modelclass.http.bean.OrderModelResponse;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.utils.CreateFileUtils;
import com.moyun.modelclass.utils.GlideEngine;
import com.moyun.modelclass.utils.StatusBarUtil;
import com.moyun.modelclass.view.MyEditText;
import com.moyun.modelclass.view.NonScrollRecyclerView;
import com.moyun.modelclass.view.recyclerview.DividerItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Notes：订单评价
 */
public class OrderEvaluateActivity extends BaseModelActivity implements OrderEvaluateModelAdapter.OnAddNewImageClick {
    private RelativeLayout llOrderEvaluateTop;
    private ImageView ivOrderEvaluateBack;
    private RatingBar ratingOrderEvaluateOne;
    private FrameLayout flOrderEvaluateImageAddOne;
    private RecyclerView recyclerOrderEvaluateImageAddOne;
    private MyEditText etOrderEvaluateTitleOne;
    private NonScrollRecyclerView recyclerOrderEvaluateModel;

    private RatingBar ratingOrderEvaluateThree;
    //    private ImageView ivOrderEvaluateImageThree;
//    private ImageView ivOrderEvaluateImageDeleteThree;
    private FrameLayout flOrderEvaluateImageAddThree;
    private RecyclerView recyclerOrderEvaluateImageAddThree;
    private MyEditText etOrderEvaluateTitleThree;
    private TextView tvOrderEvaluateIssue;

    private OrderEvaluateImageAdapter imageOneAdapter = new OrderEvaluateImageAdapter();
    private OrderEvaluateModelAdapter orderEvaluateModelAdapter = new OrderEvaluateModelAdapter();
    private OrderEvaluateImageAdapter imageThreeAdapter = new OrderEvaluateImageAdapter();

    private String mOrderId = "";

    public static void start(Context mContext, String orderId) {
        Intent starter = new Intent(mContext, OrderEvaluateActivity.class);
        starter.putExtra("orderId", orderId);
        mContext.startActivity(starter);
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_order_evaluate;
    }

    @Override
    protected void assignViews() {
        llOrderEvaluateTop = (RelativeLayout) findViewById(R.id.ll_order_evaluate_top);
        ivOrderEvaluateBack = (ImageView) findViewById(R.id.iv_order_evaluate_back);
        ratingOrderEvaluateOne = (RatingBar) findViewById(R.id.rating_order_evaluate_one);
        flOrderEvaluateImageAddOne = (FrameLayout) findViewById(R.id.fl_order_evaluate_image_add_one);
        recyclerOrderEvaluateImageAddOne = (RecyclerView) findViewById(R.id.recycler_order_evaluate_image_add_one);
        etOrderEvaluateTitleOne = (MyEditText) findViewById(R.id.et_order_evaluate_title_one);
        recyclerOrderEvaluateModel = (NonScrollRecyclerView) findViewById(R.id.recycler_order_evaluate_model);

        ratingOrderEvaluateThree = (RatingBar) findViewById(R.id.rating_order_evaluate_three);
//        ivOrderEvaluateImageThree = (ImageView) findViewById(R.id.iv_order_evaluate_image_three);
//        ivOrderEvaluateImageDeleteThree = (ImageView) findViewById(R.id.iv_order_evaluate_image_delete_three);
        recyclerOrderEvaluateImageAddThree = (RecyclerView) findViewById(R.id.recycler_order_evaluate_image_add_three);
        flOrderEvaluateImageAddThree = (FrameLayout) findViewById(R.id.fl_order_evaluate_image_add_three);
        etOrderEvaluateTitleThree = (MyEditText) findViewById(R.id.et_order_evaluate_title_three);

        tvOrderEvaluateIssue = (TextView) findViewById(R.id.tv_order_evaluate_issue);

        StatusBarUtil.setPaddingSmart(this, llOrderEvaluateTop);

        recyclerOrderEvaluateImageAddOne.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerOrderEvaluateImageAddOne.setAdapter(imageOneAdapter);

        recyclerOrderEvaluateModel.setLayoutManager(new LinearLayoutManager(mContext));
        orderEvaluateModelAdapter.setOnAddNewImageClick(this);
        recyclerOrderEvaluateModel.addItemDecoration(new DividerItemDecoration(mContext, Color.parseColor("#EFEFEF"), 1, 0, 0, true));
        recyclerOrderEvaluateModel.setAdapter(orderEvaluateModelAdapter);

        recyclerOrderEvaluateImageAddThree.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerOrderEvaluateImageAddThree.setAdapter(imageThreeAdapter);
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(ivOrderEvaluateBack, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        imageOneAdapter.setOnImageClick(new OrderEvaluateImageAdapter.OnImageClick() {
            @Override
            public void delete(int position) {
                imageOneAdapter.removeAt(position);
            }
        });

        imageThreeAdapter.setOnImageClick(new OrderEvaluateImageAdapter.OnImageClick() {
            @Override
            public void delete(int position) {
                imageThreeAdapter.removeAt(position);
            }
        });

        ClickUtils.applySingleDebouncing(flOrderEvaluateImageAddOne, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                XXPermissions.with(OrderEvaluateActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onGranted(List<String> permissions, boolean all) {
                                PictureSelector.create(OrderEvaluateActivity.this)
                                        .openGallery(SelectMimeType.ofImage())
                                        .setImageEngine(GlideEngine.createGlideEngine())
                                        .setMaxSelectNum(1)
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(ArrayList<LocalMedia> result) {
                                                for (LocalMedia media : result) {
                                                    Luban.with(OrderEvaluateActivity.this)
                                                            .load(media.getRealPath())
                                                            .ignoreBy(50)
                                                            .setTargetDir(CreateFileUtils.getSandboxPath(OrderEvaluateActivity.this))
                                                            .setCompressListener(new OnCompressListener() {
                                                                                     @Override
                                                                                     public void onStart() {
                                                                                     }

                                                                                     @Override
                                                                                     public void onSuccess(int index, File compressFile) {
//                                                                                         Glide.with(OrderEvaluateActivity.this)
//                                                                                                 .load(PictureMimeType.isContent(media.getPath()) && !media.isCut() && !media.isCompressed() ? Uri.parse(media.getPath()) : media.getPath())
//                                                                                                 .centerInside()
//                                                                                                 .diskCacheStrategy(DiskCacheStrategy.ALL)
//                                                                                                 .into(ivOrderEvaluateImageOne);
                                                                                         initUpdateImageApi(true, 1, compressFile, -1);
                                                                                     }

                                                                                     @Override
                                                                                     public void onError(int index, Throwable e) {
                                                                                     }
                                                                                 }
                                                            ).launch();
                                                }
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });
                            }

                            @Override
                            public void onDenied(List<String> permissions, boolean never) {
                                ToastUtils.showShort("获取存储权限失败");
                            }
                        });
            }
        });

        ClickUtils.applySingleDebouncing(flOrderEvaluateImageAddThree, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                XXPermissions.with(OrderEvaluateActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onGranted(List<String> permissions, boolean all) {
                                PictureSelector.create(OrderEvaluateActivity.this)
                                        .openGallery(SelectMimeType.ofImage())
                                        .setImageEngine(GlideEngine.createGlideEngine())
                                        .setMaxSelectNum(1)
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(ArrayList<LocalMedia> result) {
                                                for (LocalMedia media : result) {
                                                    Luban.with(OrderEvaluateActivity.this)
                                                            .load(media.getRealPath())
                                                            .ignoreBy(50)
                                                            .setTargetDir(CreateFileUtils.getSandboxPath(OrderEvaluateActivity.this))
                                                            .setCompressListener(new OnCompressListener() {
                                                                                     @Override
                                                                                     public void onStart() {
                                                                                     }

                                                                                     @Override
                                                                                     public void onSuccess(int index, File compressFile) {
//                                                                                         Glide.with(OrderEvaluateActivity.this)
//                                                                                                 .load(PictureMimeType.isContent(media.getPath()) && !media.isCut() && !media.isCompressed() ? Uri.parse(media.getPath()) : media.getPath())
//                                                                                                 .centerInside()
//                                                                                                 .diskCacheStrategy(DiskCacheStrategy.ALL)
//                                                                                                 .into(ivOrderEvaluateImageThree);
                                                                                         initUpdateImageApi(true, 3, compressFile, -1);
                                                                                     }

                                                                                     @Override
                                                                                     public void onError(int index, Throwable e) {
                                                                                     }
                                                                                 }
                                                            ).launch();
                                                }
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });
                            }

                            @Override
                            public void onDenied(List<String> permissions, boolean never) {
                                ToastUtils.showShort("获取存储权限失败");
                            }
                        });
            }
        });

        ClickUtils.applySingleDebouncing(tvOrderEvaluateIssue, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<OrderEvaluateApi.OrderEvaluateRequest> orderEvaluateList = new ArrayList<>();
                OrderEvaluateApi.OrderEvaluateRequest evaluateOne = new OrderEvaluateApi.OrderEvaluateRequest();
                evaluateOne.setCommentContent(etOrderEvaluateTitleOne.getText().toString().trim());
//                List<String> imageOne = new ArrayList<>();
//                imageOne.add(imageOneBean);
                evaluateOne.setImages(imageOneAdapter.getData());
                evaluateOne.setType(1);
                evaluateOne.setTargetId(mOrderId);
                evaluateOne.setStar((int) ratingOrderEvaluateOne.getRating());
                orderEvaluateList.add(evaluateOne);

                for (OrderModelResponse response : orderEvaluateModelAdapter.getData()) {
                    OrderEvaluateApi.OrderEvaluateRequest evaluateTwo = new OrderEvaluateApi.OrderEvaluateRequest();
                    evaluateTwo.setCommentContent(response.getCommentContent());
//                    List<String> imageTwo = new ArrayList<>();
//                    imageTwo.add(response.getCommentImages());
                    evaluateTwo.setImages(response.getCommentImages());
                    evaluateTwo.setType(3);
                    evaluateTwo.setTargetId(response.getModelId());
                    evaluateTwo.setStar((int) response.getStar());
                    orderEvaluateList.add(evaluateTwo);
                }

                OrderEvaluateApi.OrderEvaluateRequest evaluateThree = new OrderEvaluateApi.OrderEvaluateRequest();
                evaluateThree.setCommentContent(etOrderEvaluateTitleThree.getText().toString().trim());
//                List<String> imageThree = new ArrayList<>();
//                imageThree.add(imageThreeBean);
                evaluateThree.setImages(imageThreeAdapter.getData());
                evaluateThree.setType(2);
                evaluateThree.setTargetId(mOrderId);
                evaluateThree.setStar((int) ratingOrderEvaluateThree.getRating());
                orderEvaluateList.add(evaluateThree);

                initCommentMakeApi(orderEvaluateList);
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {
        mOrderId = bundle.getString("orderId", "");
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        initOrderDetailsApi(mOrderId);
    }


    //通过模型id列表批量获取模型数据
    @SuppressLint("SetTextI18n")
    private void initOrderDetailsApi(String mOrderId) {
        if (mOrderId.isEmpty()) {
            return;
        }
        EasyHttp.post(this)
                .api(new OrderDetailsApi().setOrderId(mOrderId))
                .request(new HttpCallback<HttpData<OrderDetailsResponse>>(this) {
                    @Override
                    public void onSucceed(HttpData<OrderDetailsResponse> result) {
                        if (result != null && result.getData() != null) {
                            orderEvaluateModelAdapter.setList(result.getData().getModelList());
                        }
                    }
                });
    }

    private void initCommentMakeApi(List<OrderEvaluateApi.OrderEvaluateRequest> commentList) {
        if (mOrderId.isEmpty()) {
            return;
        }
        EasyHttp.post(this).api(new OrderEvaluateApi().setOrderId(mOrderId).setCommentObjectList(commentList))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
                        ToastUtils.showShort("评论成功");
                        finish();
                    }
                });
    }

    @Override
    public void addNewImage(int currentPosition) {
        XXPermissions.with(OrderEvaluateActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        PictureSelector.create(OrderEvaluateActivity.this)
                                .openGallery(SelectMimeType.ofImage())
                                .setImageEngine(GlideEngine.createGlideEngine())
                                .setMaxSelectNum(1)
                                .forResult(new OnResultCallbackListener<LocalMedia>() {
                                    @Override
                                    public void onResult(ArrayList<LocalMedia> result) {
                                        showProgressDialog();
                                        for (LocalMedia media : result) {
                                            Luban.with(OrderEvaluateActivity.this)
                                                    .load(media.getRealPath())
                                                    .ignoreBy(50)
                                                    .setTargetDir(CreateFileUtils.getSandboxPath(OrderEvaluateActivity.this))
                                                    .setCompressListener(new OnCompressListener() {
                                                                             @Override
                                                                             public void onStart() {
                                                                             }

                                                                             @Override
                                                                             public void onSuccess(int index, File compressFile) {
                                                                                 initUpdateImageApi(true, 2, compressFile, currentPosition);
                                                                             }

                                                                             @Override
                                                                             public void onError(int index, Throwable e) {
                                                                                 dismissProgressDialog();
                                                                             }
                                                                         }
                                                    ).launch();
                                        }
                                    }

                                    @Override
                                    public void onCancel() {

                                    }
                                });
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.showShort("获取存储权限失败");
                    }
                });
    }

    private void initUpdateImageApi(boolean isWatermark, int type, File imageFile, int position) {
        EasyHttp.post(this).api(new UpdateImageApi()
                        .setFileName(UUID.randomUUID() + ".jpg")
                        .setFile(imageFile)
                        .setWatermark(isWatermark))
                .request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<UpdateImageApi.Bean> result) {
                        if (result.getData() == null || result.getData().getUrl() == null) {
                            return;
                        }
                        if (type == 1) {
//                            if (imageOneBean == null || imageOneBean.isEmpty()) {
//                                imageOneBean = result.getData().getUrl();
//                            }

                            imageOneAdapter.addData(result.getData().getUrl());
//                            if (imageOneBean == null || imageOneBean.isEmpty()) {
////                                flOrderEvaluateImageAddOne.setVisibility(View.VISIBLE);
////                                ivOrderEvaluateImageOne.setVisibility(View.GONE);
//                            } else {
////                                flOrderEvaluateImageAddOne.setVisibility(View.GONE);
////                                ivOrderEvaluateImageOne.setVisibility(View.VISIBLE);
//                            }
                        } else if (type == 2) {
                            List<String> commentImages = new ArrayList<>();
                            List<String> temp = orderEvaluateModelAdapter.getData().get(position).getCommentImages();
                            if (temp != null && temp.size() > 0) {
                                commentImages.addAll(temp);
                            }
                            commentImages.add(result.getData().getUrl());
                            orderEvaluateModelAdapter.getData().get(position).setCommentImages(commentImages);
                            orderEvaluateModelAdapter.notifyItemChanged(position);
                        } else if (type == 3) {
//                            if (imageThreeBean == null || imageThreeBean.isEmpty()) {
//                                imageThreeBean = result.getData().getUrl();
//                            }
                            imageThreeAdapter.addData(result.getData().getUrl());
//                            if (imageThreeBean == null || imageThreeBean.isEmpty()) {
////                                flOrderEvaluateImageAddThree.setVisibility(View.VISIBLE);
////                                ivOrderEvaluateImageDeleteThree.setVisibility(View.GONE);
////                                ivOrderEvaluateImageThree.setVisibility(View.GONE);
//                            } else {
////                                flOrderEvaluateImageAddThree.setVisibility(View.GONE);
////                                ivOrderEvaluateImageDeleteThree.setVisibility(View.GONE);
////                                ivOrderEvaluateImageThree.setVisibility(View.VISIBLE);
//                            }
                        }
                        dismissProgressDialog();
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        dismissProgressDialog();
                    }
                });
    }
}
